﻿using AspNetMVCTodo.Models;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.VisualBasic;

namespace AspNetMVCTodo
{
    /// <summary>
    /// 填充数据
    /// </summary>
    public class SeedData
    {
        public static async Task InitializeAsync(IServiceProvider services)
        {
            // 获取一个管理 IdentityRole 类型角色的 RoleManager 实例
            var roleManager = services.GetRequiredService<RoleManager<IdentityRole>>();

            await EnsureRolesAsync(roleManager);

            var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();

            await EnsureTestAdminAsync(userManager);
        }

        //此方法查看数据库里是否存在一个 Administrator 角色。如果没有，它就创建一个。
        private static async Task EnsureRolesAsync(RoleManager<IdentityRole> roleManager)
        {
            var alreadyExists = await roleManager.RoleExistsAsync(Constants.AdministratorRole);

            if (alreadyExists) return;

            await roleManager.CreateAsync(new IdentityRole(Constants.AdministratorRole));
        }

        //如果数据库里不存在一个用户名为 admin@todo.local 的用户，这个方法将创建它并给它一个临时的密码。
        private static async Task EnsureTestAdminAsync(UserManager<ApplicationUser> userManager)
        {
            var testAdmin = await userManager.Users.Where(x => x.UserName == "admin@todo.local").SingleOrDefaultAsync();
            if (testAdmin != null) return;

            testAdmin = new ApplicationUser
            {
                UserName = "admin@todo.local",
                Email = "admin@todo.local"
            };

            await userManager.CreateAsync(testAdmin, "NotSecure123!!");

            await userManager.AddToRoleAsync(testAdmin, Constants.AdministratorRole);
        }
    }
}
